#include "Private/urlio.h"
#include <stdio.h>
#include <string.h>
#include "../Defines.h"

result_type download_file(const char* const urlName, const char* const outputFileName)
{
    FILE* outf;
    URL_FILE *handle;
    char buffer[BUFFER_SIZE];

    outf=fopen(outputFileName,"w+");
    if(!outf) 
    {
        perror("couldn't open temp output file\n");
        return FATAL_ERROR;
    }

    handle = url_fopen(urlName, "r");
    if(!handle)
    {
        //TODO: change to perror...
        printf("couldn't url_fopen() %s\n", urlName);
        fclose(outf);
        return CONNECTION_ERROR;
    }

    while(!url_feof(handle)) 
    {
        url_fgets(buffer,sizeof(buffer),handle);
        fwrite(buffer,1,strlen(buffer),outf);
    }

    url_fclose(handle);
    fclose(outf);


    return SUCCESS;
}
